package com.example.front.serivce;

import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.entity.Equipment;
import com.example.front.entity.Factory;
import com.example.front.mapper.EquipmentMapper;
import com.example.interceptor.UserContext;
import com.example.passport.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EquipmentService {
    @Resource
    EquipmentMapper equipmentMapper;

    /**
     * 创建设备
     */
    public void createEquipment(Equipment equipment) {
        User me = UserContext.getUser();
        equipmentMapper.create(equipment);
    }

    /**
     * 列出设备
     */
    public ListDto<Equipment> listEquipment(Equipment condition, Pagination pagination) {
        User user =UserContext.getUser();
        condition.setTenantId(user.getTenantId());
        long total = equipmentMapper.count(condition);
        if (total == 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }
        pagination.setTotal(total);
        List<Equipment> equipmentList = equipmentMapper.findAll(condition, pagination);
        return new ListDto(equipmentList, pagination);
    }

    /**
     * 跟新数据
     */
    public void update(@Valid Equipment equipment) {
        User me = UserContext.getUser();
        equipment.setTenantId(me.getTenantId());
        if (equipmentMapper.update(equipment) != 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 删除
     */
    public void deleteById(long id,long tenantId) {
        if (equipmentMapper.delete(id, tenantId) != 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 查询单个
     */
    public Equipment findById(long id) {
        if (id == 0){
            return null;
        }
        return equipmentMapper.findById(id);
    }

}
